﻿namespace Cos.Core.NHibernate
{
    using System.Reflection;

    using FluentNHibernate.Cfg;

    using global::NHibernate;
    using global::NHibernate.Context;

    public class NHibernateHelper
    {
        static NHibernateHelper()
        {
            var cfg = new global::NHibernate.Cfg.Configuration();
            cfg.Configure();

            SessionFactory = Fluently.Configure(cfg)
                                     .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                                     .BuildSessionFactory();
        }

        public static ISessionFactory SessionFactory { get; private set; }

        public static void BindSession(ISession session)
        {
            CurrentSessionContext.Bind(session);
        }

        public static void UnBindSession(ISessionFactory sessionFactory)
        {
            var currentSession = CurrentSessionContext.Unbind(sessionFactory);
            if (currentSession != null)
            {
                currentSession.Close();
                currentSession.Dispose();
            }
        }
    }
}

